package com.platform.modules;

import com.platform.common.web.controller.BaseController;
import com.platform.common.shiro.ShiroAuthorizingRealm;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.validation.ValidateGroup;
import com.platform.common.validation.ValidationUtil;
import com.platform.common.web.domain.AjaxResult;
import com.platform.common.web.vo.SysUserVo;
import com.platform.modules.sys.domain.SysUser;
import com.platform.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author LENOVO
 * @title: MainController
 * @date 2019-08-2116:56
 */
@Controller
@Slf4j
public class SysMainController extends BaseController {

    @Resource
    private SysUserService sysUserService;

    /**
     * 去主页面
     */
    @GetMapping(value = {"/", "/main"})
    public String main(Model model) {
        model.addAttribute("nick", ShiroUtils.getUser().getNick());
        return "index";
    }

    /**
     * 去home页面
     */
    @GetMapping("/home")
    public String home() {
        return "sys/set/home";
    }

    /**
     * 退出系统
     */
    @GetMapping(value = "/logout")
    @ResponseBody
    public AjaxResult logout() {
        try {
            ShiroUtils.getSubject().logout();
            log.info("退出成功。。。。");
        } catch (Exception ex) {
            log.error("退出异常。。。。");
        } finally {
        }
        return AjaxResult.successMsg("退出成功");
    }

    /**
     * 去self页面
     */
    @GetMapping("/self")
    public String self(Model model) {
        model.addAttribute("sysUser", getSysUser());
        return "sys/set/self";
    }

    /**
     * 去修改密码页面
     */
    @GetMapping("/password")
    public String password() {
        return "sys/set/password";
    }

    /**
     * 执行修改密码方法
     */
    @PostMapping("/updPass")
    @ResponseBody
    public AjaxResult updPass(SysUserVo userVo) {
        ValidationUtil.validate(userVo, ValidateGroup.PSW.class);
        // session 中的账号信息
        SysUser sysUser = getSysUser();
        String salt = sysUser.getSalt();
        if (!sysUser.getPassword().equals(ShiroAuthorizingRealm.md5(userVo.getPassword(), salt))) {
            return AjaxResult.fail("原密码错误");
        }
        sysUser.setPassword(ShiroAuthorizingRealm.md5(userVo.getRepassword(), salt));
        // 修改密码
        sysUserService.updPassword(sysUser);
        return AjaxResult.successMsg("修改成功");
    }

}
